import React, { useState, useEffect } from "react";
import { Spin, Empty } from "antd";
import type { TreeDataNode } from "antd";
import TreeView from "../TreeView";
import ActionFooter from "../ActionFooter";
import "./style.less";
import { User } from "../../types/user";

export interface SearchTreeResultsProps {
  existingSelectedItems?: User[];
  selectedItems?: User[];
  treeData: TreeDataNode[];
  onConfirm?: (selectedNodes: User[]) => void;
  onCancel?: () => void;
  loadData?: (treeNode: any) => Promise<any[]>;
  onCheck?: (checkedKeys: React.Key[], info: any) => void; // 添加外部 onCheck 回调
  fetchCondition?: (checkedKeys: React.Key[], info: any) => Promise<any[]>; // 新增外部传入的异步函数
}

/**
 * 搜索树结果组件 (基于TreeView实现)
 */
const SearchTreeResults: React.FC<SearchTreeResultsProps> = ({
  treeData = [],
  onConfirm,
  onCancel,
  loadData,
  selectedItems = [],
  existingSelectedItems = [],
  fetchCondition,
}) => {
  const [checkedNodes, setCheckedNodes] = useState<TreeDataNode[]>([]);

  const loading = false;
  const loadingText = "加载中...";
  const emptyText = "暂无数据";
  const maxHeight = 300;

  const [treeDisabledKeys = [], setTreeDisabledKeys] = useState<React.Key[]>(
    []
  );

  const [treeCheckedKeys = [], setTreeCheckedKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    // 从existingSelectedItems中获取选中的节点
    const treeDisabledKeys =
      existingSelectedItems?.map((item) => item.id) || [];

    setTreeDisabledKeys(treeDisabledKeys);

    const treeCheckedKeys = selectedItems?.map((item) => item.id) || [];

    // treeCheckedKeys  + treeDisabledKeys 去重
    setTreeCheckedKeys([...new Set([...treeCheckedKeys, ...treeDisabledKeys])]);
  }, [existingSelectedItems, selectedItems]);

  useEffect(() => {
    setCheckedNodes(selectedItems as []);
  }, [selectedItems]);
  // 处理树形数据，添加选中状态和展开状态

  // 计算内容区域最大高度
  // handleConfirm;
  // handleCancel;

  // 处理确认按钮点击
  const handleConfirm = () => {
    if (onConfirm) {
      onConfirm(checkedNodes as []);
    }
  };

  // const ceshi = () => {
  //   console.log("ceshi");
  //   console.log("treeData", treeData);
  //   console.log("checkedNodes", checkedNodes);
  //   console.log("treeDisabledKeys", treeDisabledKeys);
  //   console.log("treeCheckedKeys", treeCheckedKeys);
  //   console.log("existingSelectedItems", existingSelectedItems);
  // };
  const handleCancel = () => {
    onCancel?.();
  };
  const handlenCheck = async (checkedKeys: React.Key[], info: any) => {
    const { checked } = info;
    return await new Promise<TreeDataNode[]>(async (resolve, reject) => {
      console.log("info", info);

      if (!checked) {
        const checkedNodes = info.checkedNodes
          .map((node: any) => {
            return node.data;
          })
          .filter((node_1: any) => {
            return !node_1.isOrg;
          })
          .filter((node_2: any) => {
            return !treeDisabledKeys.includes(node_2.id);
          });
        setCheckedNodes(checkedNodes);
        resolve(checkedKeys as []);
      }

      const condition: any = fetchCondition
        ? await fetchCondition(checkedKeys, info)
        : [];
      if (condition.length > 100) {
        reject("ceshi");
      } else {
        const checkedNodes = [...info.checkedNodes, ...condition]
          .map((node: any) => {
            return node.data;
          })
          .filter((node_1: any) => {
            return !node_1.isOrg;
          })
          .filter((node_2: any) => {
            return !treeDisabledKeys.includes(node_2.id);
          });
        setCheckedNodes(checkedNodes);
        resolve(checkedKeys as []);
      }
    });
  };
  return (
    <div
      className={`search-tree-results`}
      style={{
        marginTop: 4,
        boxShadow: "0 3px 6px rgba(0,0,0,0.1)",
        borderRadius: 4,
        position: "fixed",
        width: "660px",
        zIndex: 100,
        maxHeight: maxHeight + 50,
        overflow: "hidden",
        background: "#fff",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <div
        className="tree-content"
        style={{ overflowY: "auto", maxHeight: maxHeight }}
      >
        {loading ? (
          <div className="tree-loading">
            <Spin size="small" />
            <div className="loading-text">{loadingText}</div>
          </div>
        ) : treeData.length === 0 ? (
          <div className="tree-empty">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={emptyText}
            />
          </div>
        ) : (
          <div className="tree-view-container">
            {/* <div className="tree-title">搜索结果</div> */}
            <TreeView
              initTreeData={treeData}
              checkedKeys={treeCheckedKeys}
              disabledKeys={treeDisabledKeys}
              loadData={loadData}
              onCheck={handlenCheck as any}
            />
          </div>
        )}
      </div>

      {treeData.length > 0 && (
        <ActionFooter
          onConfirm={handleConfirm}
          onCancel={handleCancel}
          count={checkedNodes.length}
          confirmDisabled={checkedNodes.length === 0}
          className="tree-results-footer"
        />
      )}
    </div>
  );
};

export default SearchTreeResults;
